package main

import (
	"fmt"
	"github.com/nsqio/go-nsq"
	"go-web/nsq/consumer/queue"
	"log"
	"time"
)

func bak2() {
	done := make(chan bool)
	c := queue.NewConsumer("order", "stock")
	c.Set("nsqds", []string{"39.100.58.10:4150"})
	c.Set("concurrency", 15)
	c.Set("max_attempts", 10)
	c.Set("max_in_flight", 150)
	err := c.Start(nsq.HandlerFunc(func(msg *nsq.Message) error {
		fmt.Println("customer2:", string(msg.Body))
		return nil
	}))
	if err != nil {
		fmt.Errorf(err.Error())
	}
	<-done
}

func main() {


	config := nsq.NewConfig()

	config.MaxInFlight = 1 // 代表一次推给客户端多少条消息，或者客户端准备一次性接受多少条消息
	config.Hostname = "test"
	q, _ := nsq.NewConsumer("orderCreated", "stock", config)

	//f, _ := os.Create("nsqd.log")
	//q.SetLogger(log.New(io.MultiWriter(f), "", log.LstdFlags), nsq.LogLevelInfo)

	//q.SetLogger(log.New(ioutil.Discard, "", log.LstdFlags), nsq.LogLevelInfo)

	// 多携程
	q.AddConcurrentHandlers(nsq.HandlerFunc(func(message *nsq.Message) error {

		log.Printf("Got a message: %s %s", message.ID, message.Body)
		message.DisableAutoResponse() // 禁用自动提交
		message.Requeue(time.Second * 5) // 重新放入队列消费
		message.Finish() // 手动提交消费完成，移出队列

		//var orderMsg model.OrderMsg
		//json.Unmarshal(message.Body, &orderMsg)
		//fmt.Println(orderMsg)
		//message.Finish()
		return nil
	}), config.MaxInFlight)


	//q.AddHandler(nsq.HandlerFunc(func(message *nsq.Message) error {
	//
	//	log.Printf("Got a message: %s %s", message.ID, message.Body)
	//
	//	var orderMsg model.OrderMsg
	//	json.Unmarshal(message.Body, &orderMsg)
	//	fmt.Println(orderMsg)
	//
	//	return nil
	//}))

	// 1.直连nsqd
	//conn := "39.100.58.10:4150"
	//err := q.ConnectToNSQD(conn)
	//if err != nil {
	//	log.Panic(err)
	//}


	// 2.通过 nsqlookupd 服务发现
	err := q.ConnectToNSQLookupd("39.100.58.10:4161")
	if err != nil {
		log.Panic(err)
	}

	time.Sleep(1000 * time.Second)
}
